<?php
/**
 * Created by PhpStorm.
 * User: Leslie
 * Date: 2016/6/23
 * Time: 16:29
 */

namespace app\controllers;

use app\librarys\BaseController;
use app\librarys\Inteface;
use app\models\Department;
use yii\data\Pagination;
use app\models\Integral;
use app\models\Institution;
use app\models\User;
use app\models\Manager;
use Yii;


class IntegralController extends BaseController
{
    public static $pageSize = 10;
    public static $uploadDir = '../web/uploads';

    /**
     * 积分列表主页
     * @return string
     */
    public function actionIndex()
    {
        //当前用户的机构-----------------------------------------------
        $current_console_user = Manager::getCurrentManager();
        $institution = $current_console_user['institution_code'];
        $department = $current_console_user['department']['id'];
        //---------------------------------------------------------------

        $request = \Yii::$app->request;

        //下拉选择的机构
        $institutionCode = $institution;
        if ($institutionCode == '0') {
            $institutionCode = $request->get("institutionCode");
        }

        //下拉机构列表相关数据
        $selectList = Institution::getInstitutionSelectList($institution, $institutionCode);

        $departmentId = $request->get("departmentId");

        if ($departmentId == '') {
            $departmentId = $department;
        }


        $start = $request->get("page");

        $filter = $request->get("filter");
        $startTime = $request->get("startTime");
        $endTime = $request->get("endTime");

        if ($start == '') {
            $start = '0';
        } else {
            $start = ($start - 1) * self::$pageSize;
        }

        if ($startTime == '') {
            $startTime = '0';
        }
        if ($endTime == '') {
            $endTime = '0';
        }
        if ($filter == '') {
            $filter = '0';
        }
        if ($departmentId == '') {
            $departmentId = '0';
            $departmentCode = '0';
        } else {
            $departmentCode = Department::getDepartment($departmentId)['code_tree'];
            if ($departmentCode == null || $departmentCode == '') {
                $departmentCode = '0';
            }
        }

        $total = Integral::getWalfareListTotal($startTime, $endTime, $filter, $institutionCode, $departmentCode);
        $total_page = $total['totalnum'];
        if ($total_page == 0) {
            $taotal_integral = 0;
        } else {
            $taotal_integral = $total['totalIntegral'];
        }
        $record = Integral::getWalfareList($start, self::$pageSize, $startTime, $endTime, $filter, $institutionCode, 0, $departmentCode);

        $pagination = new Pagination([
            'defaultPageSize' => self::$pageSize,
            'totalCount' => $total_page,
        ]);

        return $this->render('index',
            ['institution' => $institution,
                'selectedInstitution' => $selectList['selectedInstitution'],
                'institutionList' => $selectList['institutionList'],
                'totalIntegral' => $taotal_integral,
                'pagination' => $pagination,
                'uploadDir' => self::$uploadDir,
                'record' => $record,
                'startTime' => $startTime,
                'endTime' => $endTime,
                'filter' => $filter,
                'department' => $department,
                'selectedDepartment' => $departmentId]);
    }

    /**
     * 导入excel
     * @return string
     * @throws \PHPExcel_Exception
     */
    public function actionImportIntegralList()
    {
        $request = \Yii::$app->request;

        //下拉选择的机构
        $institutionId = $request->get("institutionCode");
        //$institutionId=0;
        $departmentId = $request->get("departmentId");


        $flag = 0;
        $msg = "";

        $amount = 0;
        $iCount = 0;

        $right_data = array();
        $error_data = array();
        $ignore_data = array();

        $file = $_FILES['file']['name'];
        if ($_POST) {
            if (empty($file)) {
                $flag = 2;
                $msg = json_encode("请选择要上传的文件");
            } else {
                $file_info = pathinfo($file);
                $file_ext = $file_info['extension'];

                if (!in_array($file_ext, array('xls', 'xlsx'))) {
                    $flag = 2;
                    $msg = json_encode("文件类型不正确，仅支持xls,xlsx类型的文件！");
                } else {
                    $objPHPExcel = \PHPExcel_IOFactory::load($_FILES['file']['tmp_name']);

                    $sheet = $objPHPExcel->getSheet(0);
                    $highestRow = $sheet->getHighestRow();           //取得总行数
                    $highestColumn = $sheet->getHighestColumn(); //取得总列

                    if ($highestRow > 5002) {
                        $flag = 2;
                        $msg = json_encode("一次导入数据不能超过5000条记录！");
                    } else {

                        for ($j = 2; $j <= $highestRow; $j++)                        //从第二行开始读取数据
                        {
                            $is_error = 0;
                            $v = array();

                            for ($k = 'A'; $k <= $highestColumn; $k++)            //从A列读取数据
                            {
                                $value = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();//读取单元格
                                $v['error'] = "";

                                //获取数据
                                switch ($k) {
                                    case 'A':
                                        $v['usercode'] = trim($value);
                                        break;
                                    case 'B':
                                        $v['phone'] = trim($value);
                                        break;
                                    case 'C':
                                        $v['username'] = trim($value);
                                        break;
                                    case 'D':
                                        $v['integral'] = trim($value);
                                        break;
                                }
                                //echo $value.'&nbsp';
                            }

                            if (!($v['integral'] == "" || $v['integral'] == '0')) {

                                if ($v['phone'] == "") {
                                    $v['error'] .= '手机号码不允许为空！';
                                    $is_error = 1;
                                    $flag = 1;

                                } else {
                                    //检查用户是否存在，不存在则新增用户
                                    $record['id'] = 0;
                                    $record['code'] = 0;
                                    $record['name'] = $v['username'];
                                    $record['institution_code'] = $institutionId;
                                    $record['phone'] = $v['phone'];
                                    $record['remark'] = '';
                                    $record['isEnabled'] = 1;
                                    $record['wx_openid'] = '';
                                    $record['header_url'] = '';
                                    $record['department_id'] = $departmentId;

                                    $result = User::addUser($record);

                                    if ($result['userId'] == '0') {
                                        $v['error'] .= '新增用户失败！';
                                        $is_error = 1;
                                        $flag = 1;
                                    } else {
                                        $v['id'] = $result['userId'];
                                    }
                                }

                                if (is_numeric($v['integral'])) {
                                    $v['integral'] = (int)$v['integral'];
                                    $amount = $amount + $v['integral'];

                                } else {
                                    //echo $v['weixinid'] . '积分非数字' . '<br>';
                                    $v['error'] .= '发放积分不为数字。';
                                    $is_error = 1;
                                    $flag = 1;
                                }

                                //正确的数据 装入到正确记录数组
                                //错误的数据 装入到错误记录数组
                                if ($is_error) {
                                    $error_data[] = $v;
                                } else if ($v['integral'] > 0) {
                                    $iCount++;
                                    $right_data[] = $v;
                                } else {
                                    $ignore_data[] = $v;
                                }
                            }
                        }
                        $msg = json_encode($error_data);
                    }

                }
            }
        }

        return $this->renderJson(['right_data' => $right_data, 'amount' => $amount, 'iCount' => $iCount, 'ins' => $institutionId], $flag, $msg);
    }

    /**
     * 确认发分
     * @return string
     */
    public function actionSaveIntegralSendRecordHandler()
    {
        //当前操作人员id----------------
        $current_console_user = Manager::getCurrentManager();
        $operator_id = $current_console_user['id'];
        //------------------------------

        $request = \Yii::$app->request;
        $institutionId = $request->post('institutionId');
        $reason = $request->post('reason');
        $walfare_type = $request->post('walfareType');
        $userIntegrals = $request->post('userintegrals');
        $departmentId = $request->post('departmentId');

        $message = "";
        $data['operator_id'] = $operator_id;
        $data['institutionId'] = $institutionId;
        $data['reason'] = $reason;
        $data['walfare_type'] = $walfare_type;
        $data['userintegrals'] = $userIntegrals;
        $data['departmentId'] = $departmentId;
        $status = Integral::addInstituonUserIntegral($data);

        switch ($walfare_type) {
            case 1:
                $walfare_type = '福利';
                break;
            case 2:
                $walfare_type = '奖励';
                break;
            default:
                $walfare_type = '福利';
        }
        //发短信
        if ($status == 0) {
            $Institution = Institution::getInstitution($data['institutionId']);
            foreach ($userIntegrals as $record) {
                $user = User::getUser($record['id']);
                Inteface::sendSms($user['phone'], 58135, [$Institution['name'] . '  因[' . $reason . ']', '[' . $walfare_type . ']' . $record['integral'], 'http://' . $_SERVER['HTTP_HOST'] . '/' . $Institution['code'] . ' ']);
            }
        }

        return $this->renderJson(0, $status, $message);
    }

    /**
     * 福利详情概要
     * @return string
     */
    public function actionWalfareSummaryPartview()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');
        $walfare = Integral::getWalfareList(0, 1, 0, 0, 0, 0, $id);
        $walfare_sumarry = $walfare[0];
        $total = Integral::getWalfareUserTotal(0, $id);
        $walfare_sumarry['totalnum'] = $total['totalnum'];
        $walfare_sumarry['totalsum'] = intval($total['integral']);
        $walfare_sumarry['totalmoney'] = round($total['integral'] / $walfare_sumarry['integral_rate'], 2);
        $walfare_sumarry['integral_rate'] = intval($walfare_sumarry['integral_rate']);
        return $this->renderPartial('walfare-summary-partview', ['walfare_sumarry' => $walfare_sumarry]);
    }

    /**
     * 福利详情
     * @return string
     */
    public function actionWalfareDetailPartview()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');
        $page = $request->post("page");
        $start = $page;

        $filter = $request->post("filter");
        if ($start == '') {
            $start = 0;
            $page = 1;
        } else {
            $start = ($start - 1) * self::$pageSize;
        }
        if ($filter == '') {
            $filter = 0;
        }

        $total = Integral::getWalfareUserTotal($filter, $id);
        $record = Integral::getWalfareUserList($start, self::$pageSize, $filter, $id);

        $paginationDetail['page'] = $page;
        $paginationDetail['totalPage'] = ceil($total['totalnum'] / self::$pageSize);

        return $this->renderPartial('walfare-detail-partview', ['paginationDetail' => $paginationDetail, 'record' => $record, 'filter' => $filter]);
    }

    /**
     * 发放积分预算控制
     * @return string
     */
    public function actionWalfareBudgetList()
    {

        $institution_code = Manager::getCurrentManager()['institution_code'];

        if ($institution_code == '0') {
            $institution_code = Yii::$app->request->get('inst', '');
        }
        //返回时如果未选择机构则返回当前用户所属机构
        if ($institution_code == null || $institution_code == '') {
            //当前用户的机构-----------------------------------------------
            $current_console_user = Manager::getCurrentManager();
            $institution = $current_console_user['institution_code'];
            //---------------------------------------------------------------
            $institution_code = $institution;
        }
        $list = [];
        if ($institution_code != null && $institution_code != '') {
            //查询分类LIST
            $list = [];
//            $list = Goods::getGoodsExtendCategoryList($institution_code);
        }


        //返回结果
        return $this->render('walfare-budget-list', ['list' => $list, 'institution_code' => $institution_code]);
    }

    public function actionWalfareBudgetEditView()
    {
        $institution_code = Manager::getCurrentManager()['institution_code'];

        if ($institution_code == '0') {
            $institution_code = Yii::$app->request->get('inst', '');
        }
        //返回时如果未选择机构则返回当前用户所属机构
        if ($institution_code == null || $institution_code == '') {
            //当前用户的机构-----------------------------------------------
            $current_console_user = Manager::getCurrentManager();
            $institution = $current_console_user['institution_code'];
            //---------------------------------------------------------------
            $institution_code = $institution;
        }

        return $this->renderPartial('walfare-budget-edit-view', [
            'detail' => null,
            'institution_code' => $institution_code,
        ]);
    }

    public function actionTest()
    {
        $session = \Yii::$app->session;
        $current_console_user = $session->get(Manager::SessionKey);
        echo($current_console_user['id']);
        exit();
    }
}